package swu.cx.finalproject

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_first.*


class TouchUnlockView:View {
    //记录原始密码
    var orgPwd:String?=null
    var mylistener: firstActivity? = null
    //保存圆的半径
    private var radius = 0f
    //保存圆之间的间距
    private var padding = 0f
    //利用数组，保存所有9个点的信息对象
    private val dotInfos = mutableListOf<DotInfo>()
    //保存所有被点亮的点的信息
    private val selectedItems = mutableListOf<DotInfo>()
    //保存上一个被点亮的圆点信息
    private var lastSelectedItem: DotInfo? = null
    //记录移动时触摸点的坐标 也即移动线条的终点
    private val endPoint = Point()
    //记录线条的路径
    private val linePath = Path()
    //线的画笔
    private val linePaint = Paint().apply {
        color = Color.WHITE
        style = Paint.Style.STROKE
        strokeWidth = 5f
    }
    //圆圈内部的白色遮盖的圆
    private val innerCirclePaint = Paint().apply {
        color = Color.BLUE
        style = Paint.Style.FILL
    }
    //记录密码（两次的）
    private var password = StringBuilder()
    //记录临时密码(第一次的)
    private var firstPwd: String? = null
    //记录上下文
    private var mContext: Context? = null

    //代码创建
    constructor(context: Context): super(context){

    }

    //xml创建
    constructor(context: Context,attrs: AttributeSet?):super(context,attrs){

    }

    //xml style
    constructor(context: Context,attrs: AttributeSet?,style: Int):super(context,attrs,style){

    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //初始化
        init()
    }

    override fun onDraw(canvas: Canvas?) {
        //绘制线（要在点的前面）
        canvas?.drawPath(linePath,linePaint)

        //绘制移动的线
        if(!endPoint.equals(0,0)) {
            canvas?.drawLine(lastSelectedItem!!.cx,lastSelectedItem!!.cy,
                             endPoint.x.toFloat(),endPoint.y.toFloat(),
                             linePaint)
        }
        //绘制九个点
        drawNineDot(canvas)
    }

    //绘制9个点
    fun drawNineDot(canvas: Canvas?){
        for (info in dotInfos){
            canvas?.drawCircle(info.cx,info.cy,info.radius,info.paint)
            canvas?.drawCircle(info.cx,info.cy,info.radius - 5,innerCirclePaint)
            if(info.isSelected){
                canvas?.drawCircle(info.cx,info.cy,info.innerCircleRadius,info.paint)
            }
        }
    }
    //做初始化
    private fun init(){
        //第一个点的中心点
        var cx = 0f
        var cy = 0f

        //计算半径和间距
        //判断用户设置当前View的尺寸，确保在正方形区域绘制
        if(measuredWidth >= measuredHeight){
            //半径
            radius = measuredHeight/5/2f
            //间距
            padding = (measuredHeight - 3*radius*2) / 4
            //中心点
            cx = (measuredWidth - measuredHeight)/2f + padding + radius
            cy = padding + radius
        }else{
            //半径
            radius = measuredWidth/5/2f
            //间距
            padding = (measuredWidth - 3*radius*2) / 4
            //中心点
            cx = padding + radius
            cy = (measuredHeight - measuredWidth)/2f + padding + radius
        }

        //设置9个点组成的Path
        for(row in 0..2){
            for(colum in 0..2){
                DotInfo(cx + colum*(2*radius+padding),
                           cy + row*(2*radius + padding),
                           radius,row*3 + colum + 1).also {
                             dotInfos.add(it)
                            }
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        //获取触摸点的坐标
        val x = event?.x
        val y = event?.y

        when(event?.action){
            MotionEvent.ACTION_DOWN ->{
                //判断这个点是否在某个矩形区域内
                containsPoint(x,y).also {
                    if(it != null){
                        //在某个圆点内
                        //点亮这个点
                        selectItem(it)
                        //linePath的起点
                        linePath.moveTo(it.cx,it.cy)
                    }
                }
            }

            MotionEvent.ACTION_MOVE ->{
                //判断这个点是否在某个矩形区域内
                containsPoint(x,y).also {
                    if(it != null){
                        //在某个圆点内
                        //点亮这个点
                        if(!it.isSelected) {
                            //没有点亮
                            //先判断是不是第一个点
                            if(lastSelectedItem == null){
                                //就是第一个点
                                //linePath的起点
                                linePath.moveTo(it.cx,it.cy)
                            }else{
                                //从上一个点到当前点化画线
                                linePath.lineTo(it.cx,it.cy)
                            }
                            //点亮这个点
                            selectItem(it)
                        }
                    }else{
                        //触摸点在外部
                        if(lastSelectedItem != null){
                            endPoint.set(x!!.toInt(),y!!.toInt())
                            invalidate()
                        }
                    }
                }
            }
            MotionEvent.ACTION_UP ->{
                reset()

            }
        }
        return true
    }

    //重新设置
    private fun reset(){
        //将颜色改回正常颜色
        for(item in selectedItems){
            item.isSelected = false
        }

        //线条重设
        linePath.reset()

        invalidate()

        //清空
        selectedItems.clear()
        if (orgPwd!=null){
            firstPwd = password.toString()
            if (orgPwd==firstPwd) {
                mylistener!!.textView.text = "密码正确"
                Toast.makeText(mylistener, "登录成功", Toast.LENGTH_LONG).show()
                //进行页面跳转
                mylistener?.jumpPage()
            }else{
                mylistener!!.textView.text = "密码错误，请重新绘制！！"
                password.clear()
            }
            return
        }
        if(firstPwd == null){
            firstPwd = password.toString()
            mylistener!!.textView.text = "请重新确认密码"
        }else{
            //是第二次
            if(firstPwd == password.toString()){
                //说明两次输入的密码一致
                //保存密码
                SharedPreferenceUtil.getInstance(mContext!!).savePassword(firstPwd.toString())
                Toast.makeText(mylistener,"登录成功", Toast.LENGTH_LONG).show()
                //进行页面跳转
                mylistener?.jumpPage()
            }else{
                //说明两次密码输入的不一致
                mylistener?.textView?.text= "您两次密码输入不一致，请重新输入"
                doSecond()
            }
        }
        password.delete(0,password.length)
    }

    //第二次输入密码错误的时候执行的东西
    private fun doSecond(){
        //将颜色改回正常颜色
        for(item in selectedItems){
            item.isSelected = false
        }

        //线条重设
        linePath.reset()

        invalidate()

        //清空
        selectedItems.clear()
    }

    //点亮某个点
    private fun selectItem(item: DotInfo){
        //设置这个点已经被选中
        item.isSelected = true
        //立刻刷新，重新绘制
        invalidate()//调用它，onDraw方法会重新执行
        //保存点亮的这个点
        selectedItems.add(item)
        //记录这个点
        lastSelectedItem = item
        //设置endPoint为空
        endPoint.set(0,0)
        //记录当前的密码
        password.append(item.tag)
    }

    //查找某个矩形区域是否包含触摸点
    private fun containsPoint(x: Float?,y: Float?):DotInfo?{
        for(item in dotInfos){
            if(item.rect.contains(x!!.toInt(),y!!.toInt())){
                return item
            }
        }
        return null
    }

    fun SetListener(listener: firstActivity){
        mylistener = listener
        mContext = listener
    }
}